import 'package:flutter/foundation.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:get/get.dart';
import 'package:jump_scape/js_data/js_box/js_coin_shop.dart';
import 'package:jump_scape/js_data/js_box/js_setting.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import 'package:uuid/uuid.dart';

import '../../objectbox.g.dart';
import 'js_game_record.dart';
import 'js_member.dart';

/// flutter pub run build_runner build
class JsObjectBox {
  static late final JsObjectBox _box;
  late final Store store;

  JsObjectBox._create(this.store) {
    store.box<SettingBox>().getAll().forEach((setting) {
      debugPrint("[setting] ✅ $setting");
    });

    store.box<MemberBox>().getAll().forEach((member) {
      debugPrint("[member] ✅ $member");
    });

    store.box<CoinShopBox>().getAll().forEach((coinShop) {
      debugPrint("[coinShop] ✅ $coinShop");
    });
  }

  static Future<void> create() async {
    final docsDir = await getApplicationDocumentsDirectory();
    final store = await openStore(directory: p.join(docsDir.path, "obx"));
    _box = JsObjectBox._create(store);
  }

  static Box<SettingBox> get settingBox => _box.store.box<SettingBox>();

  static Box<MemberBox> get memberBox => _box.store.box<MemberBox>();

  static Box<CoinShopBox> get coinShopBox => _box.store.box<CoinShopBox>();

  static Box<GameRecordBox> get gameRecordBox => _box.store.box<GameRecordBox>();

  static Future<SettingBox> get setting async {
    if (!settingBox.contains(1)) {
      String deviceId = '';
      try {
        FlutterSecureStorage _secureStorage = FlutterSecureStorage();
        deviceId = (await _secureStorage.read(key: 'jump_scape_id')) ?? '';
      } catch (e) {
        e.printError();
      }
      if (deviceId.isEmpty) {
        deviceId = const Uuid().v4();
        try {
          FlutterSecureStorage _secureStorage = FlutterSecureStorage();
          _secureStorage.write(key: 'jump_scape_id', value: deviceId);
        } catch (e) {
          e.printError();
        }
      }

      final setting = SettingBox(id: 1, deviceId: deviceId, userToken: '', userId: '', appConfigVer: '0', firstLaunchTime: DateTime.now(), googleTranslationKey: '');
      settingBox.put(setting);
      debugPrint("[Setting] ✅ $setting");
    }
    return settingBox.get(1)!;
  }
}
